package io.github.rascaler.dcenter.message;

import io.github.rascaler.dcenter.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 默认异常码加载器
 * @ClassName MessageLoader
 * @Description TODO
 * @Author wurenqing
 * @Date 2022/7/5 9:48
 */
@Slf4j
public class DefaultErrorMessageManager implements ErrorMessageManager {
    List<ErrorMessageLoader> messageLoaders = new ArrayList<>();

    private static Map<String,String> messages = new HashMap<>();

    @Autowired
    private PropertiesErrorMessageLoader propertiesMessageLoader;

    public void init() {
        // 初始化异常码加载器
        BizException.messageManager = this;
        this.addLoader(propertiesMessageLoader);
    }

    // 获取消息
    public String getMsg(String code) {
        String msg = messages.get(code);
        if (StringUtils.isEmpty(msg)) {
            throw new RuntimeException(String.format("code=[%s]消息未定义", code));
        }
        return msg;
    }

    // 用于扩展加异常码加载器
    public void addLoader(ErrorMessageLoader messageLoader) {
        messageLoaders.add(messageLoader);
        Map<String, String> msgs = messageLoader.load();
        // 检查重复
        List<String> list = msgs.keySet().stream().filter(it->messages.keySet().contains(it)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            messages.putAll(msgs);
        } else {
            log.error(String.format("异常码定义重复,请检查,code=[%s]", String.join(",", list)));
            throw new RuntimeException(String.format("异常码定义重复,请检查,code=[%s]", String.join(",", list)));
        }
    }

    // 用于刷新替换
    public void refresh(String key,String value) {
        messages.put(key, value);
    }
}
